package core

import "github.com/xuri/excelize/v2"

var columns = []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
	"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
var maxColumns = getMaxColumns()

// getMaxColumns 获取列数组, 最大26+ 26*26列
func getMaxColumns() []string {
	res := make([]string, 0, 26*27)

	// copy A-Z
	for _, column := range columns {
		res = append(res, column)
	}
	for _, v := range columns {
		for _, c := range columns {
			res = append(res, v+c)
		}
	}

	return res
}

type Xlsx struct {
	file         *excelize.File      // file 数据表
	sheets       []string            // sheets 全部sheet名称
	columns      map[string][]string // columns 列名称, [A, B, C]
	columnLength map[string]int      // columnLength 列长
	lastColumn   map[string]string   // lastColumn 最后一列
}

func NewXlsx(file *excelize.File) (x *Xlsx) {
	x = &Xlsx{
		file:         file,
		sheets:       file.GetSheetList(),
		columns:      map[string][]string{},
		columnLength: map[string]int{},
		lastColumn:   map[string]string{},
	}

	for _, sheet := range x.sheets {
		rows, err := x.file.GetRows(sheet)
		if err != nil {
			return
		}
		if len(rows) > 0 {
			l := len(rows[0])
			x.columns[sheet] = maxColumns[0:l]
			x.columnLength[sheet] = l

			if l > 0 {
				x.lastColumn[sheet] = maxColumns[l-1]
			}
		}
	}
	return
}

func (x *Xlsx) NextColumns(sheet string, size int) []string {
	return maxColumns[x.columnLength[sheet] : x.columnLength[sheet]+size]
}
